package com.liu.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.liu.controller.dto.DepDTO;
import com.liu.controller.dto.HosDepDTO;
import com.liu.controller.dto.PasswordDTO;
import com.liu.controller.dto.UserDTO;
import com.liu.entity.*;
import com.liu.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (Physician)表控制层
 *
 * @author makejava
 * @since 2023-02-11 13:34:03
 */
@RestController
@RequestMapping("/physician")
@CrossOrigin
@Slf4j
public class PhysicianController {
    /**
     * 医师对象
     */
    private PhysicianService physicianService;
    @Autowired
    @Qualifier("physicianServiceImpl")
    public void setPhysicianService(PhysicianService physicianService){
        this.physicianService = physicianService;
    }

    /**
     * 评论对象
     */
    private AppraiseService appraiseService;
    @Autowired
    @Qualifier("appraiseServiceImpl")
    public void setService(AppraiseService appraiseService){
        this.appraiseService = appraiseService;
    }

    /**
     * 医院对象
     */
    private HospitalService hospitalService;
    @Autowired
    @Qualifier("hospitalServiceImpl")
    public void setService(HospitalService hospitalService){
        this.hospitalService = hospitalService;
    }

    /**
     * 服务对象
     */
    private DepartmentService departmentService;
    @Autowired
    @Qualifier("departmentServiceImpl")
    public void setService(DepartmentService departmentService){
        this.departmentService = departmentService;
    }


    /**
     * 登录
     * @param userDTO
     * @return
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody UserDTO userDTO, HttpSession session) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        Map<String, Object> result = new HashMap<>();
        log.info("登录的用户名:{} 登录的密码:{}", username, password);
        HashMap<String, Object> map = new HashMap<>();
        map.put("username",username);
        map.put("password",password);
        try {
            Physician physicianDB = physicianService.login(map);
            log.info("登录的用户:{}", physicianDB.toString());
            result.put("success", true);
            result.put("data", physicianDB);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("data", e.getMessage());
        }
        return result;
    }

    /**
     * 注册
     * @param userDTO
     * @return
     */
    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody UserDTO userDTO){
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        Map<String, Object> map = new HashMap<>();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            map.put("success",false);
            map.put("message","用户名或密码为空");
            return map;
        }
        Physician physicianDB = physicianService.findByName(username);
        if(physicianDB != null){
            map.put("success",false);
            map.put("message","该用户名已存在");
            return map;
        }
        Physician physician = new Physician();
        physician.setUsername(username);
        physician.setPassword(password);
        physician.setNickname(userDTO.getNickname());
        physicianService.insert(physician);
        map.put("success",true);
        map.put("message","注册成功");
        return map;
    }

    /**
     * 查询所有医生
     * @param nickname
     * @param identity
     * @param grade
     * @param name
     * @return
     */
    @GetMapping("/findAllPhy")
    public Map<String, Object> findAllPhy(@RequestParam(defaultValue = "") String nickname,
                                          @RequestParam(defaultValue = "") String identity,
                                          @RequestParam(defaultValue = "") String grade,
                                          @RequestParam(defaultValue = "") String name
                                          ) {
        List<Physician> data = physicianService.findAllPhy(nickname, identity, grade, name);
        Long total = physicianService.allCount(nickname, identity, grade, name);
        Map<String, Object> map = new HashMap<>();
        map.put("data",data);
        map.put("total",total);
        return map;
    }

    /**
     * 医生总数
     * @param username
     * @param identity
     * @return
     */
    @GetMapping("/count")
    public Long findCount(@RequestParam(defaultValue = "") String username,
                         @RequestParam(defaultValue = "") String identity) {
        return physicianService.count(username,identity);
    }

    /**
     * 对应医院科室医师数量
     * @param id 医院id
     * @return
     */
    @GetMapping("/findDepCount")
    public List<DepDTO> findDepCount(@RequestParam(defaultValue = "") Integer id){
        log.info("id: {}",id);
        List<DepDTO> phyCount = physicianService.findPhyCount(id);
        log.info("科室信息: {}",phyCount);
        return phyCount;
    }

    /**
     * 查询所有
     *
     */
    @GetMapping("/list")
    public List<Physician> findAll(){
        return physicianService.findAll();
    }

    /**
     * 查看所有医院
     * @return
     */
    @GetMapping("/findHos")
    public List<Hospital> findHos() {
        return hospitalService.findAll(null,null,null,null);
    }

    /**
     * 查看所有科室
     * @return
     */
    @GetMapping("/findDep")
    public List<Department> findDep() {
        return departmentService.findAll();
    }

    /**
     * 根据科室类型查找医师
     * @param department
     * @return
     */
    @PostMapping("/selectPhyByDep")
    public List<Physician> selectPhyByDep(@RequestBody Department department){
        log.info("科室：{}",department);
        return physicianService.selectPhyByDep(department.getName());
    }

    /**
     * 根据医院科室找医师
     * @return
     */
    @GetMapping("/findPhy")
    public Map<String, Object> findPhy(@RequestParam Integer hosId,
                                   @RequestParam(defaultValue = "") Integer depId){
        HosDepDTO hosDepDTO = new HosDepDTO();
        hosDepDTO.setHosId(hosId);
        hosDepDTO.setDepId(depId);
        List<Physician> data = physicianService.findPhy(hosDepDTO);
        Long total = physicianService.phyCount(hosDepDTO);
        Map<String,Object> res = new HashMap<>();
        res.put("data",data);
        res.put("total",total);
        return res;
    }

    /**
     * 根据科室Id查找医生
     * @param id
     * @return
     */
    @PostMapping("/findPhyByDepId")
    public List<Physician> findPhyByDepId(Integer id){
        return physicianService.findPhyByDepId(id);
    }

    /**
     * 查看对应医院有排班的医生
     * @param pageNum
     * @param pageSize
     * @param hosId
     * @param depId
     * @return
     */
    @GetMapping("/findPhyStage")
    public Map<String, Object> findPhyStage(@RequestParam Integer pageNum,
                                            @RequestParam Integer pageSize,
                                            @RequestParam Integer hosId,
                                            @RequestParam Integer depId){
        log.info("hosId: {}, depId: {}",hosId,depId);
        pageNum = (pageNum - 1) * pageSize;
        List<Physician> data = physicianService.queryAllPhyStage(pageNum, pageSize,hosId,depId);
        log.info("医生：{}",data.toString());
        int total = data.size();
        Map<String,Object> res = new HashMap<>();
        res.put("data",data);
        res.put("total",total);
        return res;
    }

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Map<String, Object> findPage(@RequestParam Integer pageNum,
                                        @RequestParam Integer pageSize,
                                        @RequestParam(defaultValue = "") String username,
                                        @RequestParam(defaultValue = "") String identity){
        pageNum = (pageNum - 1) * pageSize;
        List<Physician> data = physicianService.queryAllByLimit(pageNum, pageSize, username, identity);
        log.info("医生：{}",data.size());
        Long total = physicianService.count(username,identity);
        Map<String,Object> res = new HashMap<>();
        res.put("data",data);
        res.put("total",total);
        return res;
    }

    /**
     * 添加或更新
     *
     * @param physician
     */
    @PostMapping("/editUser")
    public int insert(@RequestBody Physician physician) {
        log.info("当前保存或修改用户信息:{}", physician.toString());
        //根据传递过来的参数studentId是否存在来决定进入哪个方法
        if (physician.getId() != null && physician.getId().toString().length() > 0) {
            System.out.println(physician.getId());
            return physicianService.update(physician);
        } else {
            System.out.println(physician.getId());
            return physicianService.insert(physician);
        }
    }

    /**
     * 修改密码
     * @param passwordDTO
     * @return
     */
    @PostMapping("/password")
    public int updatePwd(@RequestBody PasswordDTO passwordDTO){
        return physicianService.updatePwd(passwordDTO);
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/delUser")
    public int deleteUser(Integer id){
        log.info("当前删除用户的id:{}", id);
        return physicianService.deleteById(id);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping("/delBatch")
    public int deleteBatch(@RequestBody List<Integer> ids){
        return physicianService.deleteByIds(ids);
    }

    /**
     * 导出文件
     * @param response
     * @throws Exception
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        //从数据库查询所有数据
        List<Physician> list = physicianService.findAll();
        //在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
//        writer.addHeaderAlias("id","ID");
        //一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list,true);

        //设置浏览器响应格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset-utf-8");
        String fileName = URLEncoder.encode("医师信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out,true);
        out.close();
        writer.close();
    }

    /**
     * 导入文件
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public int imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<Physician> list = reader.readAll(Physician.class);
        System.out.println(list);
        return physicianService.insertBatch(list);
    }

    /**
     * 根据id查找
     * @param id
     * @return
     */
    @GetMapping("/findById")
    public Physician findById(Integer id){
        return physicianService.queryById(id);
    }


    /**
     * 根据用户名查找
     * @param username
     * @return
     */
    @PostMapping("/findByName")
    public Physician findByName(String username){
        return physicianService.findByName(username);
    }

}

